package com.zhoutao.blog.seven.service.impl;

import com.zhoutao.blog.seven.dao.model.BookChapterDao;
import com.zhoutao.blog.seven.dao.model.BookDao;
import com.zhoutao.blog.seven.dao.repository.BookChapterRepository;
import com.zhoutao.blog.seven.dao.repository.BookRepository;
import com.zhoutao.blog.seven.model.converter.BookChapterConverter;
import com.zhoutao.blog.seven.model.response.BookChapter;
import com.zhoutao.blog.seven.service.BookChapterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class BookChapterServiceImpl implements BookChapterService {

    private final BookChapterRepository chapterRepository;

    private final BookRepository bookRepository;

    private final BookChapterConverter chapterConverter;


    @Override
    public List<BookChapter> findByBookKey(String bookKey) {
        BookDao bookDao = bookRepository.findByKey(bookKey);
        if (bookDao == null) {
            return Collections.emptyList();
        }
        return findByBookId(bookDao.getId());
    }

    @Override
    public List<BookChapter> findByBookId(Long bookId) {
        List<BookChapterDao> chapters = chapterRepository.findByBookId(bookId);
        if (CollectionUtils.isEmpty(chapters)) {
            return Collections.emptyList();
        }
        return chapters.stream().map(chapterConverter::converterFrom).collect(Collectors.toList());
    }
}
